<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="根据 raft 协议可知，当整个集群完成 Leader 选主后，集群中的主节点就可以接受客户端的请求，而集群中的从节点只负责从主节点同步数据，而不会处理读写请求，与M-S结构的读写分离有着巨大的区别。 有了前篇文章的基础，本文将直接从 Leader 处理客户端请求入口开始，其入口为：DLedgerServer 的 handleAppend 方法开始讲起。 1、日志复制基本流程在正式分析 Rocke">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析 RocketMQ DLedger(多副本) 之日志追加流程">
<meta property="og:url" content="https://www.codingw.net/posts/d35cbb14.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="根据 raft 协议可知，当整个集群完成 Leader 选主后，集群中的主节点就可以接受客户端的请求，而集群中的从节点只负责从主节点同步数据，而不会处理读写请求，与M-S结构的读写分离有着巨大的区别。 有了前篇文章的基础，本文将直接从 Leader 处理客户端请求入口开始，其入口为：DLedgerServer 的 handleAppend 方法开始讲起。 1、日志复制基本流程在正式分析 Rocke">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20190914204415722.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2020-10-17T12:07:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:08:34.780Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20190914204415722.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/d35cbb14.html"/>





  <title>源码分析 RocketMQ DLedger(多副本) 之日志追加流程 | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/d35cbb14.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析 RocketMQ DLedger(多副本) 之日志追加流程</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-10-17T20:07:01+08:00">
                2020-10-17
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/rocketmq/" itemprop="url" rel="index">
                    <span itemprop="name">rocketmq</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/d35cbb14.html" class="leancloud_visitors" data-flag-title="源码分析 RocketMQ DLedger(多副本) 之日志追加流程">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>根据 raft 协议可知，当整个集群完成 Leader 选主后，集群中的主节点就可以接受客户端的请求，而集群中的从节点只负责从主节点同步数据，而不会处理读写请求，与M-S结构的读写分离有着巨大的区别。</p>
<p>有了前篇文章的基础，本文将直接从 Leader 处理客户端请求入口开始，其入口为：DLedgerServer 的 handleAppend 方法开始讲起。</p>
<h2 id="1、日志复制基本流程"><a href="#1、日志复制基本流程" class="headerlink" title="1、日志复制基本流程"></a>1、日志复制基本流程</h2><p>在正式分析 RocketMQ DLedger 多副本复制之前，我们首先来了解客户端发送日志的请求协议字段，其类图如下所示：<br><img src="https://img-blog.csdnimg.cn/20190914204415722.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>我们先一一介绍各个字段的含义：</p>
<ul>
<li>String group<br>该集群所属组名。</li>
<li>String remoteId<br>请求目的节点ID。</li>
<li>String localId<br>节点ID。</li>
<li>int code<br>请求响应字段，表示返回响应码。</li>
<li>String leaderId = null<br>集群中的Leader Id。</li>
<li>long term<br>集群当前的选举轮次。</li>
<li>byte[] body<br>待发送的数据。</li>
</ul>
<p>日志的请求处理处理入口为 DLedgerServer 的 handleAppend 方法。</p>
<p>DLedgerServer#handleAppend</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">PreConditions.check(memberState.getSelfId().equals(request.getRemoteId()), DLedgerResponseCode.UNKNOWN_MEMBER, <span class="string">&quot;%s != %s&quot;</span>, request.getRemoteId(), memberState.getSelfId());</span><br><span class="line">reConditions.check(memberState.getGroup().equals(request.getGroup()), DLedgerResponseCode.UNKNOWN_GROUP, <span class="string">&quot;%s != %s&quot;</span>, request.getGroup(), memberState.getGroup());</span><br><span class="line">PreConditions.check(memberState.isLeader(), DLedgerResponseCode.NOT_LEADER);</span><br></pre></td></tr></table></figure>
<p>Step1：首先验证请求的合理性：</p>
<ul>
<li>如果请求的节点ID不是当前处理节点，则抛出异常。</li>
<li>如果请求的集群不是当前节点所在的集群，则抛出异常。</li>
<li>如果当前节点不是主节点，则抛出异常。</li>
</ul>
<p>DLedgerServer#handleAppend</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">long</span> currTerm = memberState.currTerm();</span><br><span class="line"><span class="keyword">if</span> (dLedgerEntryPusher.isPendingFull(currTerm)) &#123;  <span class="comment">// @1</span></span><br><span class="line">    AppendEntryResponse appendEntryResponse = <span class="keyword">new</span> AppendEntryResponse();</span><br><span class="line">    appendEntryResponse.setGroup(memberState.getGroup());</span><br><span class="line">    appendEntryResponse.setCode(DLedgerResponseCode.LEADER_PENDING_FULL.getCode());</span><br><span class="line">    appendEntryResponse.setTerm(currTerm);</span><br><span class="line">    appendEntryResponse.setLeaderId(memberState.getSelfId());</span><br><span class="line">    <span class="keyword">return</span> AppendFuture.newCompletedFuture(-<span class="number">1</span>, appendEntryResponse);</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;   <span class="comment">// @2</span></span><br><span class="line">    DLedgerEntry dLedgerEntry = <span class="keyword">new</span> DLedgerEntry();</span><br><span class="line">    dLedgerEntry.setBody(request.getBody());</span><br><span class="line">    DLedgerEntry resEntry = dLedgerStore.appendAsLeader(dLedgerEntry);</span><br><span class="line">    <span class="keyword">return</span> dLedgerEntryPusher.waitAck(resEntry);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step2：如果预处理队列已经满了，则拒绝客户端请求，返回 LEADER_PENDING_FULL 错误码；如果未满，将请求封装成 DledgerEntry，则调用 dLedgerStore 方法追加日志，并且通过使用 dLedgerEntryPusher 的 waitAck 方法同步等待副本节点的复制响应，并最终将结果返回给调用方法。</p>
<ul>
<li>代码@1：如果 dLedgerEntryPusher 的 push 队列已满，则返回追加一次，其错误码为 LEADER_PENDING_FULL。</li>
<li>代码@2：追加消息到 Leader 服务器，并向从节点广播，在指定时间内如果未收到从节点的确认，则认为追加失败。</li>
</ul>
<p>接下来就按照上述三个要点进行展开：</p>
<ul>
<li>判断 Push 队列是否已满</li>
<li>Leader 节点存储消息</li>
<li>主节点等待从节点复制 ACK</li>
</ul>
<h3 id="1-1-如何判断-Push-队列是否已满"><a href="#1-1-如何判断-Push-队列是否已满" class="headerlink" title="1.1  如何判断 Push 队列是否已满"></a>1.1  如何判断 Push 队列是否已满</h3><p>DLedgerEntryPusher#isPendingFull</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isPendingFull</span><span class="params">(<span class="keyword">long</span> currTerm)</span> </span>&#123;</span><br><span class="line">    checkTermForPendingMap(currTerm, <span class="string">&quot;isPendingFull&quot;</span>);     <span class="comment">// @1</span></span><br><span class="line">    <span class="keyword">return</span> pendingAppendResponsesByTerm.get(currTerm).size() &gt; dLedgerConfig.getMaxPendingRequestsNum(); <span class="comment">// @2</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>主要分两个步骤：<br>代码@1：检查当前投票轮次是否在 PendingMap 中，如果不在，则初始化，其结构为：Map&lt; Long/* 投票轮次*/, ConcurrentMap&lt;Long, TimeoutFuture&lt; AppendEntryResponse&gt;&gt;&gt;。</p>
<p>代码@2：检测当前等待从节点返回结果的个数是否超过其最大请求数量，可通过maxPendingRequests<br>Num 配置，该值默认为：10000。</p>
<p>上述逻辑比较简单，但疑问随着而来，ConcurrentMap&lt;Long, TimeoutFuture&lt; AppendEntryResponse&gt;&gt; 中的数据是从何而来的呢？我们不妨接着往下看。</p>
<span id="more"></span>

<h3 id="1-2-Leader-节点存储数据"><a href="#1-2-Leader-节点存储数据" class="headerlink" title="1.2  Leader 节点存储数据"></a>1.2  Leader 节点存储数据</h3><p>Leader 节点的数据存储主要由 DLedgerStore 的 appendAsLeader 方法实现。DLedger 分别实现了基于内存、基于文件的存储实现，本文重点关注基于文件的存储实现，其实现类为：DLedgerMmapFileStore。</p>
<p>下面重点来分析一下数据存储流程，其入口为DLedgerMmapFileStore 的 appendAsLeader 方法。</p>
<p>DLedgerMmapFileStore#appendAsLeader</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">PreConditions.check(memberState.isLeader(), DLedgerResponseCode.NOT_LEADER);</span><br><span class="line">PreConditions.check(!isDiskFull, DLedgerResponseCode.DISK_FULL);</span><br></pre></td></tr></table></figure>
<p>Step1：首先判断是否可以追加数据，其判断依据主要是如下两点：</p>
<ul>
<li>当前节点的状态是否是 Leader，如果不是，则抛出异常。</li>
<li>当前磁盘是否已满，其判断依据是 DLedger 的根目录或数据文件目录的使用率超过了允许使用的最大值，默认值为85%。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ByteBuffer dataBuffer = localEntryBuffer.get();</span><br><span class="line">ByteBuffer indexBuffer = localIndexBuffer.get();</span><br></pre></td></tr></table></figure>
<p>Step2：从本地线程变量获取一个数据与索引 buffer。其中用于存储数据的 ByteBuffer，其容量固定为 4M ，索引的 ByteBuffer 为两个索引条目的长度，固定为64个字节。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">DLedgerEntryCoder.encode(entry, dataBuffer);</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">encode</span><span class="params">(DLedgerEntry entry, ByteBuffer byteBuffer)</span> </span>&#123;</span><br><span class="line">    byteBuffer.clear();</span><br><span class="line">    <span class="keyword">int</span> size = entry.computSizeInBytes();</span><br><span class="line">    <span class="comment">//always put magic on the first position</span></span><br><span class="line">    byteBuffer.putInt(entry.getMagic());</span><br><span class="line">    byteBuffer.putInt(size);</span><br><span class="line">    byteBuffer.putLong(entry.getIndex());</span><br><span class="line">    byteBuffer.putLong(entry.getTerm());</span><br><span class="line">    byteBuffer.putLong(entry.getPos());</span><br><span class="line">    byteBuffer.putInt(entry.getChannel());</span><br><span class="line">    byteBuffer.putInt(entry.getChainCrc());</span><br><span class="line">    byteBuffer.putInt(entry.getBodyCrc());</span><br><span class="line">    byteBuffer.putInt(entry.getBody().length);</span><br><span class="line">    byteBuffer.put(entry.getBody());</span><br><span class="line">    byteBuffer.flip();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step3：将 DLedgerEntry，即将数据写入到 ByteBuffer中，从这里看出，每一次写入会调用 ByteBuffer 的 clear 方法，将数据清空，从这里可以看出，每一次数据追加，只能存储4M的数据。</p>
<p>DLedgerMmapFileStore#appendAsLeader</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">synchronized</span> (memberState) &#123;</span><br><span class="line">    PreConditions.check(memberState.isLeader(), DLedgerResponseCode.NOT_LEADER, <span class="keyword">null</span>);</span><br><span class="line">	<span class="comment">// ... 省略代码</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step4：锁定状态机，并再一次检测节点的状态是否是 Leader 节点。</p>
<p>DLedgerMmapFileStore#appendAsLeader</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">long</span> nextIndex = ledgerEndIndex + <span class="number">1</span>;</span><br><span class="line">entry.setIndex(nextIndex);</span><br><span class="line">entry.setTerm(memberState.currTerm());</span><br><span class="line">entry.setMagic(CURRENT_MAGIC);</span><br><span class="line">DLedgerEntryCoder.setIndexTerm(dataBuffer, nextIndex, memberState.currTerm(), CURRENT_MAGIC);</span><br></pre></td></tr></table></figure>
<p>Step5：为当前日志条目设置序号，即 entryIndex 与 entryTerm (投票轮次)。并将魔数、entryIndex、entryTerm 等写入到 bytebuffer 中。</p>
<p>DLedgerMmapFileStore#appendAsLeader</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">long</span> prePos = dataFileList.preAppend(dataBuffer.remaining());</span><br><span class="line">entry.setPos(prePos);</span><br><span class="line">PreConditions.check(prePos != -<span class="number">1</span>, DLedgerResponseCode.DISK_ERROR, <span class="keyword">null</span>);</span><br><span class="line">DLedgerEntryCoder.setPos(dataBuffer, prePos);</span><br></pre></td></tr></table></figure>
<p>Step6：计算新的消息的起始偏移量，关于 dataFileList 的 preAppend 后续详细介绍其实现，然后将该偏移量写入日志的 bytebuffer 中。</p>
<p>DLedgerMmapFileStore#appendAsLeader</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (AppendHook writeHook : appendHooks) &#123;</span><br><span class="line">    writeHook.doHook(entry, dataBuffer.slice(), DLedgerEntry.BODY_OFFSET);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Step7：执行钩子函数。</p>
<p>DLedgerMmapFileStore#appendAsLeader</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">long</span> dataPos = dataFileList.append(dataBuffer.array(), <span class="number">0</span>, dataBuffer.remaining());</span><br><span class="line">PreConditions.check(dataPos != -<span class="number">1</span>, DLedgerResponseCode.DISK_ERROR, <span class="keyword">null</span>);</span><br><span class="line">PreConditions.check(dataPos == prePos, DLedgerResponseCode.DISK_ERROR, <span class="keyword">null</span>);</span><br></pre></td></tr></table></figure>
<p>Step8：将数据追加到 pagecache 中。该方法稍后详细介绍。</p>
<p>DLedgerMmapFileStore#appendAsLeader</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">DLedgerEntryCoder.encodeIndex(dataPos, entrySize, CURRENT_MAGIC, nextIndex, memberState.currTerm(), indexBuffer);</span><br><span class="line"><span class="keyword">long</span> indexPos = indexFileList.append(indexBuffer.array(), <span class="number">0</span>, indexBuffer.remaining(), <span class="keyword">false</span>);</span><br><span class="line">PreConditions.check(indexPos == entry.getIndex() * INDEX_UNIT_SIZE, DLedgerResponseCode.DISK_ERROR, <span class="keyword">null</span>);</span><br></pre></td></tr></table></figure>
<p>Step9：构建条目索引并将索引数据追加到 pagecache。</p>
<p>DLedgerMmapFileStore#appendAsLeader</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">ledgerEndIndex++;</span><br><span class="line">ledgerEndTerm = memberState.currTerm();</span><br><span class="line"><span class="keyword">if</span> (ledgerBeginIndex == -<span class="number">1</span>) &#123;</span><br><span class="line">    ledgerBeginIndex = ledgerEndIndex;</span><br><span class="line">&#125;</span><br><span class="line">updateLedgerEndIndexAndTerm();</span><br></pre></td></tr></table></figure>
<p>Step10：ledgerEndeIndex 加一（下一个条目）的序号。并设置 leader 节点的状态机的 ledgerEndIndex 与 ledgerEndTerm。</p>
<p>Leader 节点数据追加就介绍到这里，稍后会重点介绍与存储相关方法的实现细节。</p>
<h3 id="1-3-主节点等待从节点复制-ACK"><a href="#1-3-主节点等待从节点复制-ACK" class="headerlink" title="1.3 主节点等待从节点复制 ACK"></a>1.3 主节点等待从节点复制 ACK</h3><p>其实现入口为 dLedgerEntryPusher 的 waitAck 方法。</p>
<p>DLedgerEntryPusher#waitAck</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> CompletableFuture&lt;AppendEntryResponse&gt; <span class="title">waitAck</span><span class="params">(DLedgerEntry entry)</span> </span>&#123;</span><br><span class="line">    updatePeerWaterMark(entry.getTerm(), memberState.getSelfId(), entry.getIndex());    <span class="comment">// @1</span></span><br><span class="line">    <span class="keyword">if</span> (memberState.getPeerMap().size() == <span class="number">1</span>) &#123;                                                                  <span class="comment">// @2</span></span><br><span class="line">        AppendEntryResponse response = <span class="keyword">new</span> AppendEntryResponse();</span><br><span class="line">        response.setGroup(memberState.getGroup());</span><br><span class="line">        response.setLeaderId(memberState.getSelfId());</span><br><span class="line">        response.setIndex(entry.getIndex());</span><br><span class="line">        response.setTerm(entry.getTerm());</span><br><span class="line">        response.setPos(entry.getPos());</span><br><span class="line">        <span class="keyword">return</span> AppendFuture.newCompletedFuture(entry.getPos(), response);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        checkTermForPendingMap(entry.getTerm(), <span class="string">&quot;waitAck&quot;</span>);                                            </span><br><span class="line">        AppendFuture&lt;AppendEntryResponse&gt; future = <span class="keyword">new</span> AppendFuture&lt;&gt;(dLedgerConfig.getMaxWaitAckTimeMs()); <span class="comment">// @3</span></span><br><span class="line">        future.setPos(entry.getPos());</span><br><span class="line">        CompletableFuture&lt;AppendEntryResponse&gt; old = pendingAppendResponsesByTerm.get(entry.getTerm()).put(entry.getIndex(), future);     <span class="comment">// @4</span></span><br><span class="line">        <span class="keyword">if</span> (old != <span class="keyword">null</span>) &#123;</span><br><span class="line">            logger.warn(<span class="string">&quot;[MONITOR] get old wait at index=&#123;&#125;&quot;</span>, entry.getIndex());</span><br><span class="line">        &#125;</span><br><span class="line">        wakeUpDispatchers();                                       <span class="comment">// @5</span></span><br><span class="line">        <span class="keyword">return</span> future;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：更新当前节点的 push 水位线。<br>代码@2：如果集群的节点个数为1，无需转发，直接返回成功结果。<br>代码@3：构建 append 响应 Future 并设置超时时间，默认值为：2500 ms，可以通过 maxWaitAckTimeMs 配置改变其默认值。<br>代码@4：将构建的 Future 放入等待结果集合中。<br>代码@5：唤醒 Entry 转发线程，即将主节点中的数据 push 到各个从节点。</p>
<p>接下来分别对上述几个关键点进行解读。</p>
<h4 id="1-3-1-updatePeerWaterMark-方法"><a href="#1-3-1-updatePeerWaterMark-方法" class="headerlink" title="1.3.1 updatePeerWaterMark 方法"></a>1.3.1 updatePeerWaterMark 方法</h4><p>DLedgerEntryPusher#updatePeerWaterMark</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">updatePeerWaterMark</span><span class="params">(<span class="keyword">long</span> term, String peerId, <span class="keyword">long</span> index)</span> </span>&#123;    <span class="comment">// 代码@1</span></span><br><span class="line">    <span class="keyword">synchronized</span> (peerWaterMarksByTerm) &#123; </span><br><span class="line">       checkTermForWaterMark(term, <span class="string">&quot;updatePeerWaterMark&quot;</span>);                     <span class="comment">// 代码@2</span></span><br><span class="line">        <span class="keyword">if</span> (peerWaterMarksByTerm.get(term).get(peerId) &lt; index) &#123;                   <span class="comment">// 代码@3</span></span><br><span class="line">            peerWaterMarksByTerm.get(term).put(peerId, index);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：先来简单介绍该方法的两个参数：</p>
<ul>
<li>long term<br>当前的投票轮次。</li>
<li>String peerId<br>当前节点的ID。</li>
<li>long index<br>当前追加数据的序号。</li>
</ul>
<p>代码@2：初始化 peerWaterMarksByTerm 数据结构，其结果为 &lt; Long /** term  */, Map&lt; String /** peerId */, Long /** entry index*/&gt;。</p>
<p>代码@3：如果 peerWaterMarksByTerm 存储的 index 小于当前数据的 index，则更新。</p>
<h4 id="1-3-2-wakeUpDispatchers-详解"><a href="#1-3-2-wakeUpDispatchers-详解" class="headerlink" title="1.3.2  wakeUpDispatchers 详解"></a>1.3.2  wakeUpDispatchers 详解</h4><p>DLedgerEntryPusher#updatePeerWaterMark</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">wakeUpDispatchers</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (EntryDispatcher dispatcher : dispatcherMap.values()) &#123;</span><br><span class="line">        dispatcher.wakeup();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>该方法主要就是遍历转发器并唤醒。本方法的核心关键就是 EntryDispatcher，在详细介绍它之前我们先来看一下该集合的初始化。</p>
<p>DLedgerEntryPusher 构造方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (String peer : memberState.getPeerMap().keySet()) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!peer.equals(memberState.getSelfId())) &#123;</span><br><span class="line">        dispatcherMap.put(peer, <span class="keyword">new</span> EntryDispatcher(peer, logger));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>原来在构建 DLedgerEntryPusher 时会为每一个从节点创建一个 EntryDispatcher 对象。</p>
<p>显然，日志的复制由 DLedgerEntryPusher 来实现。由于篇幅的原因，该部分内容将在下篇文章中继续。</p>
<p>上面在讲解 Leader 追加日志时并没有详细分析存储相关的实现，为了知识体系的完备，接下来我们来分析一下其核心实现。</p>
<h2 id="2、日志存储实现详情"><a href="#2、日志存储实现详情" class="headerlink" title="2、日志存储实现详情"></a>2、日志存储实现详情</h2><p>本节主要对 MmapFileList 的 preAppend 与 append 方法进行详细讲解。</p>
<blockquote>
<p>存储部分的设计请查阅笔者的博客：<a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/100177780">源码分析 RocketMQ DLedger 多副本存储实现</a>，MmapFileList 对标 RocketMQ 的MappedFileQueue。</p>
</blockquote>
<h3 id="2-1-MmapFileList-的-preAppend-详解"><a href="#2-1-MmapFileList-的-preAppend-详解" class="headerlink" title="2.1 MmapFileList 的 preAppend 详解"></a>2.1 MmapFileList 的 preAppend 详解</h3><p>该方法最终会调用两个参数的 preAppend方法，故我们直接来看两个参数的 preAppend 方法。</p>
<p>MmapFileList#preAppend</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">preAppend</span><span class="params">(<span class="keyword">int</span> len, <span class="keyword">boolean</span> useBlank)</span> </span>&#123;                <span class="comment">// @1</span></span><br><span class="line">    MmapFile mappedFile = getLastMappedFile();                   <span class="comment">// @2 start</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">null</span> == mappedFile || mappedFile.isFull()) &#123;</span><br><span class="line">        mappedFile = getLastMappedFile(<span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">null</span> == mappedFile) &#123;</span><br><span class="line">        logger.error(<span class="string">&quot;Create mapped file for &#123;&#125;&quot;</span>, storePath);</span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    &#125;                                                                                            <span class="comment">// @2 end</span></span><br><span class="line">    <span class="keyword">int</span> blank = useBlank ? MIN_BLANK_LEN : <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span> (len + blank &gt; mappedFile.getFileSize() - mappedFile.getWrotePosition()) &#123;   <span class="comment">// @3</span></span><br><span class="line">        <span class="keyword">if</span> (blank &lt; MIN_BLANK_LEN) &#123;</span><br><span class="line">            logger.error(<span class="string">&quot;Blank &#123;&#125; should ge &#123;&#125;&quot;</span>, blank, MIN_BLANK_LEN);</span><br><span class="line">            <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            ByteBuffer byteBuffer = ByteBuffer.allocate(mappedFile.getFileSize() - mappedFile.getWrotePosition());     <span class="comment">// @4</span></span><br><span class="line">            byteBuffer.putInt(BLANK_MAGIC_CODE);                                                                                                      <span class="comment">// @5</span></span><br><span class="line">            byteBuffer.putInt(mappedFile.getFileSize() - mappedFile.getWrotePosition());                                               <span class="comment">// @6</span></span><br><span class="line">            <span class="keyword">if</span> (mappedFile.appendMessage(byteBuffer.array())) &#123;                                                                                     <span class="comment">// @7</span></span><br><span class="line">                <span class="comment">//need to set the wrote position</span></span><br><span class="line">                mappedFile.setWrotePosition(mappedFile.getFileSize());</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                logger.error(<span class="string">&quot;Append blank error for &#123;&#125;&quot;</span>, storePath);</span><br><span class="line">                <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            mappedFile = getLastMappedFile(<span class="number">0</span>);</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">null</span> == mappedFile) &#123;</span><br><span class="line">                logger.error(<span class="string">&quot;Create mapped file for &#123;&#125;&quot;</span>, storePath);</span><br><span class="line">                <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> mappedFile.getFileFromOffset() + mappedFile.getWrotePosition();<span class="comment">// @8</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先介绍其参数的含义：</p>
<ul>
<li>int len 需要申请的长度。</li>
<li>boolean useBlank 是否需要填充，默认为true。</li>
</ul>
<p>代码@2：获取最后一个文件，即获取当前正在写的文件。</p>
<p>代码@3：如果需要申请的资源超过了当前文件可写字节时，需要处理的逻辑。代码@4-@7都是其处理逻辑。</p>
<p>代码@4：申请一个当前文件剩余字节的大小的bytebuffer。</p>
<p>代码@5：先写入魔数。</p>
<p>代码@6：写入字节长度，等于当前文件剩余的总大小。</p>
<p>代码@7：写入空字节，代码@4-@7的用意就是写一条空Entry，填入魔数与 size，方便解析。</p>
<p>代码@8：如果当前文件足以容纳待写入的日志，则直接返回其物理偏移量。</p>
<p>经过上述代码解读，我们很容易得出该方法的作用，就是返回待写入日志的起始物理偏移量。</p>
<h3 id="2-2-MmapFileList-的-append-详解"><a href="#2-2-MmapFileList-的-append-详解" class="headerlink" title="2.2 MmapFileList 的 append 详解"></a>2.2 MmapFileList 的 append 详解</h3><p>最终会调用4个参数的 append 方法，其代码如下：<br>MmapFileList#append</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">long</span> <span class="title">append</span><span class="params">(<span class="keyword">byte</span>[] data, <span class="keyword">int</span> pos, <span class="keyword">int</span> len, <span class="keyword">boolean</span> useBlank)</span> </span>&#123;  <span class="comment">// @1</span></span><br><span class="line">    <span class="keyword">if</span> (preAppend(len, useBlank) == -<span class="number">1</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    MmapFile mappedFile = getLastMappedFile();                               <span class="comment">// @2</span></span><br><span class="line">    <span class="keyword">long</span> currPosition = mappedFile.getFileFromOffset() + mappedFile.getWrotePosition();   <span class="comment">// @3</span></span><br><span class="line">    <span class="keyword">if</span> (!mappedFile.appendMessage(data, pos, len)) &#123;            <span class="comment">// @4</span></span><br><span class="line">        logger.error(<span class="string">&quot;Append error for &#123;&#125;&quot;</span>, storePath);</span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> currPosition;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先介绍一下各个参数：</p>
<ul>
<li>byte[] data<br>待写入的数据，即待追加的日志。</li>
<li>int pos<br>从 data 字节数组哪个位置开始读取。</li>
<li>int len<br>待写入的字节数量。</li>
<li>boolean useBlank<br>是否使用填充，默认为 true。</li>
</ul>
<p>代码@2：获取最后一个文件，即当前可写的文件。</p>
<p>代码@3：获取当前写入指针。</p>
<p>代码@4：追加消息。</p>
<p>最后我们再来看一下 appendMessage，具体的消息追加实现逻辑。</p>
<p>DefaultMmapFile#appendMessage</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">appendMessage</span><span class="params">(<span class="keyword">final</span> <span class="keyword">byte</span>[] data, <span class="keyword">final</span> <span class="keyword">int</span> offset, <span class="keyword">final</span> <span class="keyword">int</span> length)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> currentPos = <span class="keyword">this</span>.wrotePosition.get();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> ((currentPos + length) &lt;= <span class="keyword">this</span>.fileSize) &#123;</span><br><span class="line">        ByteBuffer byteBuffer = <span class="keyword">this</span>.mappedByteBuffer.slice(); <span class="comment">// @1</span></span><br><span class="line">        byteBuffer.position(currentPos);</span><br><span class="line">        byteBuffer.put(data, offset, length);</span><br><span class="line">        <span class="keyword">this</span>.wrotePosition.addAndGet(length);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>该方法我主要是想突出一下写入的方式是 mappedByteBuffer，是通过 FileChannel 的 map 方法创建，即我们常说的 PageCache，即消息追加首先是写入到 pageCache 中。</p>
<p><strong>本文详细介绍了 Leader 节点处理客户端消息追加请求的前面两个步骤，即 判断 Push 队列是否已满 与 Leader 节点存储消息。考虑到篇幅的问题，各个节点的数据同步将在下一篇文章中详细介绍。</strong></p>
<p>在进入下一篇的文章学习之前，我们不妨思考一下如下问题：</p>
<ol>
<li>如果主节点追加成功（写入到 PageCache)，但同步到从节点过程失败或此时主节点宕机，集群中的数据如何保证一致性？</li>
</ol>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/45a744cd.html" rel="next" title="源码分析 Sentinel DegradeSlot 熔断实现原理">
                <i class="fa fa-chevron-left"></i> 源码分析 Sentinel DegradeSlot 熔断实现原理
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/91680207.html" rel="prev" title="源码分析 RocketMQ DLedger(多副本) 之日志复制(传播)">
                源码分析 RocketMQ DLedger(多副本) 之日志复制(传播) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E6%97%A5%E5%BF%97%E5%A4%8D%E5%88%B6%E5%9F%BA%E6%9C%AC%E6%B5%81%E7%A8%8B"><span class="nav-number">1.</span> <span class="nav-text">1、日志复制基本流程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-%E5%A6%82%E4%BD%95%E5%88%A4%E6%96%AD-Push-%E9%98%9F%E5%88%97%E6%98%AF%E5%90%A6%E5%B7%B2%E6%BB%A1"><span class="nav-number">1.1.</span> <span class="nav-text">1.1  如何判断 Push 队列是否已满</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-Leader-%E8%8A%82%E7%82%B9%E5%AD%98%E5%82%A8%E6%95%B0%E6%8D%AE"><span class="nav-number">1.2.</span> <span class="nav-text">1.2  Leader 节点存储数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-%E4%B8%BB%E8%8A%82%E7%82%B9%E7%AD%89%E5%BE%85%E4%BB%8E%E8%8A%82%E7%82%B9%E5%A4%8D%E5%88%B6-ACK"><span class="nav-number">1.3.</span> <span class="nav-text">1.3 主节点等待从节点复制 ACK</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3-1-updatePeerWaterMark-%E6%96%B9%E6%B3%95"><span class="nav-number">1.3.1.</span> <span class="nav-text">1.3.1 updatePeerWaterMark 方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3-2-wakeUpDispatchers-%E8%AF%A6%E8%A7%A3"><span class="nav-number">1.3.2.</span> <span class="nav-text">1.3.2  wakeUpDispatchers 详解</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81%E6%97%A5%E5%BF%97%E5%AD%98%E5%82%A8%E5%AE%9E%E7%8E%B0%E8%AF%A6%E6%83%85"><span class="nav-number">2.</span> <span class="nav-text">2、日志存储实现详情</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-MmapFileList-%E7%9A%84-preAppend-%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 MmapFileList 的 preAppend 详解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-MmapFileList-%E7%9A%84-append-%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 MmapFileList 的 append 详解</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
